#include <stdio.h>
#include <Windows.h>
#include "Game.h"
#include "Server.h"
#include "guicon.h"
#include "BodyInfo.h"

using namespace std;

#pragma comment(lib, "ws2_32.lib")

const char TITLE[] = "Window Creation";

Game *game;
Server* server;



//************************ WIN MAIN***********************************

int WINAPI WinMain( HINSTANCE hinstance,
	HINSTANCE hprevinstance,
	LPSTR lpcmdline,
	int ncmdshow)
{

	// 3rd processor
	HANDLE threadId = GetCurrentThread();
	DWORD_PTR processAffinityMask = 4; //
	SetThreadAffinityMask(threadId, processAffinityMask);
	
	RedirectIOToConsole();
	

	game = new Game();

	server = new Server();
	server->init();
	server->start();
	server->m_game = game;
	void* addr = game->ptrCircles(); 
	server->setSendBuffer(addr);

	std::cout.precision(8);
	std::cout << std::fixed;

	///// physics loop ///////////////

	double freqPhysics = game->physicsFreq();
	float delta = 1.0f / (float)freqPhysics;

	double d0, d1, elapsedTime=0;
	int counter = 0;
	double timer = 0;
	double currentTime = 0;
	double avgElapsedTime = 0.0;
	double baseTime = game->getTime();

	game->startTimer();


	while (true) 
	{		
		currentTime = game->getTime() - baseTime;
			
		if (currentTime >= delta*counter) 
		{
			d0 = game->getTime();
				game->Update(delta);
			d1 = game->getTime();
	
			elapsedTime = d1-d0;
			counter++;

			// Things to be checked after execution of each loop ------------
			
		}


		avgElapsedTime += elapsedTime;
		timer += game->getDeltaTime();

		// Things to do per Second -----------------------------
		if (timer >= 1.0) {
			timer = 0.0;
			//------------------
			
			// average elapsedTime
			avgElapsedTime /= (double)freqPhysics;
			// get new value for baseTime
			baseTime = game->getTime();
			// inform game 
			game->periodEnd(true);

			double gameSum = 0.0;
			

			// get current value for frequency and update delta
			freqPhysics = game->physicsFreq();
			delta = 1.0f / (float)freqPhysics;

			// output
			cout << "fps: " << counter << endl;
			cout << "time: " << elapsedTime << "   " << delta << endl;
			bool output = false;
			if (output) {
				cout << "fps: " << counter << endl;
				cout << "time: " << elapsedTime << "   " << delta << endl;
				cout << "----------" << endl;
			}

			avgElapsedTime = 0;
			counter = 0;
		}
	}

	server->terminate();
	server->waitForTermination();

	delete game;

} // end WinMain


//************************ END OF WIN MAIN ***********************
